
//
//  BKIntegralCommon.m
//  bestkeep
//
//  Created by yons on 16/12/5.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKIntegralCommon.h"
#import "Mediator+BKMy.h"
#import "BKintegralModel.h"
#import "BK_OD_Tool.h"
#import "BKUserMobileConfigInfo.h"
@implementation BKIntegralCommon

+(CGPoint )point_bubbleWithTag:(int)tag{
    CGPoint  point_bubble;
    
    if (tag==1) {
        /*
         * 左上   (SCREEN_WIDTH/2.0-50,SC)
         */
        if (ScreenWidth>376) {
            point_bubble=CGPointMake(ScreenWidth/2.0-50, 50+15);
        }else{
            point_bubble=CGPointMake(ScreenWidth/2.0-50, 50);
        }
        
        
        
    }else if(tag==2){
        /*
         * 左下
         */
        if (ScreenWidth>376) {
            point_bubble=CGPointMake(ScreenWidth/2.0-50, 125+15);
        }else{
            point_bubble = CGPointMake(ScreenWidth/2.0-50, 125);
        }
        }else if(tag==3){
        
        /*
         * 右上
         */
        if (ScreenWidth>376) {
            point_bubble = CGPointMake(ScreenWidth/2.0+40, 60+15);
        }else{
            point_bubble = CGPointMake(ScreenWidth/2.0+40, 60);
        }
        
        
    }else if(tag==4){
        /*
         * 右下
         */
        if (ScreenWidth>376) {
            point_bubble = CGPointMake(ScreenWidth/2.0+45, 135+15) ;
        }else{
            point_bubble =CGPointMake(ScreenWidth/2.0+45, 135);
        }
        
    }
    
    return point_bubble;
}

+(void)BK_saveString:(NSString *)str withID:(NSString *)IDStr{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:str forKey:IDStr];
}

+(NSString *)BK_getStringwithID:(NSString *)IDStr{
    NSUserDefaults *userDsfaults = [NSUserDefaults standardUserDefaults];
    return [userDsfaults objectForKey:IDStr];
}
+(NSString *)getUserId{
    Mediator *mediator = [Mediator sharedInstance];
    NSDictionary *dic = [mediator BKMyUserInfo];
    NSString *result = dic[BKMyUserInfoGetUserIdKey];
    return result;
}
+(NSString *)getLocalKeyWithSuccess:(BOOL)success{
    
    if (success) {
        return [NSString stringWithFormat:@"Open_LocalRemind%@",[BKIntegralCommon getUserId]];
    }else{
        return [NSString stringWithFormat:@"Close_LocalRemind%@",[BKIntegralCommon getUserId]];
    }
}
/**
 *   获取字符宽度
 */
+ (CGFloat)getWidthWithTitle:(NSString *)title font:(CGFloat )font {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1000, 0)];
    label.text = title;
    label.font = [UIFont systemFontOfSize:font];
    [label sizeToFit];
    return label.frame.size.width;
}

/*
 * 检测是否打开推送
 */
+(BOOL )isOpenLocalNotification{
    BOOL isTurnOnPush = YES;
    if ([[UIDevice currentDevice].systemVersion floatValue] < 8.0) {
        if ([[UIApplication sharedApplication] enabledRemoteNotificationTypes] != UIRemoteNotificationTypeNone) {
            isTurnOnPush = YES;
        } else {
            isTurnOnPush = NO;
        }
    }
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        if ([[UIApplication sharedApplication] currentUserNotificationSettings].types == 0) {
            isTurnOnPush = NO;
        } else {
            isTurnOnPush = YES;
        }
    }
    
    return isTurnOnPush;
}
#pragma mark=====================关闭本地推送=====================
+(void)closeLocalNotification{
    //更新本地状态
    [BKIntegralCommon BK_saveString:[BKIntegralCommon getLocalKeyWithSuccess:NO] withID:LocalRemind_KEY];
    [[UIApplication sharedApplication]cancelAllLocalNotifications];
}
#pragma mark=====================开启本地推送=====================
+(void)openLocalNotification{
    //更新本地状态
    [BKIntegralCommon BK_saveString:[BKIntegralCommon getLocalKeyWithSuccess:YES] withID:LocalRemind_KEY];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //获取当前时间
    NSDate *nowDate = [NSDate date];
    NSString *dateStr = [dateFormatter stringFromDate:nowDate];
    //获取今天10：00
    NSString * str_today_date10_00 = [NSString stringWithFormat:@"%@ 10:00:00",[dateStr substringToIndex:10]];
    NSDate * today_date10_00 = [dateFormatter dateFromString:str_today_date10_00];
    //获取明天10：00
    NSString *str_tomorrow_date10_00 =[NSString stringWithFormat:@"%@ 10:00:00",[[BKIntegralCommon GetTomorrowDay:nowDate] substringToIndex:10]];
    NSDate * tomorrow_date10_00 = [dateFormatter dateFromString:str_tomorrow_date10_00];
    
    long sec;
    if([BKIntegralCommon compareDate:dateStr withDate:str_today_date10_00]==1){//还没到今天10:00
        sec =[BKIntegralCommon getSubSecFromData:nowDate ToData:today_date10_00];
    }else{
        sec =[BKIntegralCommon getSubSecFromData:nowDate ToData:tomorrow_date10_00];
    }
    
    UILocalNotification *notification = [[UILocalNotification alloc]init];
    notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:sec];
    notification.alertBody = @"新的一天开始啦!快来BESTKEEP签到吧!";
    notification.alertAction = @"签到啦";
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.userInfo = @{
                              @"body":@"BESTKEEP:签到啦"
                              };
    notification.repeatInterval = kCFCalendarUnitDay;
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];

}
//比较两个时间
+(int)compareDate:(NSString*)date01 withDate:(NSString*)date02{
    int ci;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *dt1 = [[NSDate alloc] init];
    NSDate *dt2 = [[NSDate alloc] init];
    dt1 = [df dateFromString:date01];
    dt2 = [df dateFromString:date02];
    NSComparisonResult result = [dt1 compare:dt2];
    switch (result)
    {
            //date02比date01大
        case NSOrderedAscending: ci=1; break;
            //date02比date01小
        case NSOrderedDescending: ci=-1; break;
            //date02=date01
        case NSOrderedSame: ci=0; break;
        default: NSLog(@"erorr dates %@, %@", dt2, dt1); break;
    }
    return ci;
}
//传入今天的时间，返回明天的时间
+ (NSString *)GetTomorrowDay:(NSDate *)aDate {
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
    [components setDay:([components day]+1)];
    
    NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
    NSDateFormatter *dateday = [[NSDateFormatter alloc] init];
    [dateday setDateFormat:@"yyyy-MM-dd HH:mm"];
    return [dateday stringFromDate:beginningOfWeek];
}
/*
 * 计算两个时间的差值
 */
+(long)getSubSecFromData:(NSDate *)fromDate ToData:(NSDate *)toDate{
    NSCalendar *cal = [NSCalendar currentCalendar];
    long sec;
    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *d = [cal components:unitFlags fromDate:fromDate toDate:toDate options:0];
    sec = [d hour]*3600+[d minute]*60+[d second];
    //    NSLog(@"second = %ld",[d hour]*3600+[d minute]*60+[d second]);
    return sec;
}


+(void)getUserIntegralRecord:(NSString *)pageno callback:(myCallback)callback{
    kOrderLoading;
    NSDictionary *paramDic = [NSDictionary dictionaryWithObjectsAndKeys:@"20",@"pagesize",pageno,@"pageno", nil];
    RequestManager *manager = [RequestManager manager];
    [manager bkDataRequest:RequestMethodPost URLString:[BKMainCommon ServicesURL:@"userIntegralRecord/list"] parameters:paramDic success:^(id  _Nullable responseObject) {
        kOrderDismiss;
        if (responseObject) {
            NSDictionary *result_dic = responseObject;
            BOOL success = [[result_dic objectForKey:@"success"] boolValue];
            if (success) {
                callback(YES,[result_dic  objectForKey:@"data"],nil);
            }else{
                callback(NO,result_dic,nil);
            }
        }
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        kOrderDismiss;
           callback(NO,nil,error);
    }];
}

+(void)getUserCheckInfo:(myCallback)callback{
//    kOrderLoading;
    RequestManager *manager = [RequestManager manager];
    [manager bkDataRequest:RequestMethodPost URLString:[BKMainCommon ServicesURL:@"UserCheckIn/checkInfo"] parameters:nil success:^(id  _Nullable responseObject) {
//        kOrderDismiss;
        if (responseObject) {
            NSDictionary *result_dic = responseObject;
            BOOL success = [[result_dic objectForKey:@"success" ] boolValue];
            if (success) {

//                kOrderDismiss;
                callback(YES,result_dic[@"data"],nil);
            }else{
//                kOrderDismiss;
                callback(NO,result_dic,nil);
            }
            
        }
        
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
//        kOrderDismiss;
        callback(NO,nil,error);
        
        
    }];
    
}
+(void)checkIn_callback:(myCallback)callback{
    
//    device_udid
    
//    NSString *SERVICE_NAME = @"com.utouu.bestkeep";//最好用程序的bundle id
//    NSString * str_UUID =  [BKKeychain valueForKey:SERVICE_NAME ];  // 从keychain获取数据
    BKUserMobileConfigInfo * mobileConfig = [[BKUserMobileConfigInfo alloc]init];
    kOrderLoading;
    NSDictionary *paramDic = [NSDictionary dictionaryWithObjectsAndKeys:mobileConfig.device_udid,@"device_udid", nil];
        
    RequestManager *manager = [RequestManager manager];
    [manager bkDataRequest:RequestMethodPost URLString:[BKMainCommon ServicesURL:@"UserCheckIn/checkIn"] parameters:paramDic success:^(id  _Nullable responseObject) {
        kOrderDismiss;
        if (responseObject) {
            NSDictionary *result_dic = responseObject;
            BOOL success = [[result_dic objectForKey:@"success" ] boolValue];
            if (success) {
                
                callback(YES,result_dic[@"data"],nil);
            }else{
                kOrderPromptMsg(responseObject[@"msg"]);
                callback(NO,result_dic,nil);
            }
        }
        
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        kOrderDismiss;
        NSString *errorMsg;
        if (error.code == -1001) {
            errorMsg = @"请求超时";
        }else if(error.code == 502){
            errorMsg = @"服务器开小差了，请稍后再试！";
        }else{
            errorMsg = @"请求失败";
        }
        kOrderPromptMsg(errorMsg);
        callback(NO,nil,error);
    }];
}

+ (void)integralGoods_infoExchangeId:(NSString *)exchangeId callback:(myCallback)callback{
    NSDictionary *param_dic = [NSDictionary dictionaryWithObject:exchangeId forKey:@"exchangeId"];
    RequestManager *manager = [RequestManager manager];
//    kOrderLoading;
    [manager bkDataRequest:RequestMethodPost URLString:[BKMainCommon ServicesURL:@"integralGoods/info"] parameters:param_dic success:^(id  _Nullable responseObject) {
        NSDictionary *dic = responseObject;
//         kOrderDismiss;
        if ([dic[@"success"] boolValue]){
            callback(YES,dic[@"data"],nil);
        }else{
            callback(NO,dic,nil);
        }
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
//         kOrderDismiss;
        callback(NO,nil,error);
    }];
}
+ (void)integralGoods_exchangeConfirm:(NSString *)exchangeId callback:(myCallback)callback{
    NSDictionary *param_dic = [NSDictionary dictionaryWithObject:exchangeId forKey:@"exchangeId"];
    RequestManager *manager = [RequestManager manager];
    kOrderLoading;
    [manager bkDataRequest:RequestMethodPost URLString:[BKMainCommon ServicesURL:@"integralGoods/exchangeConfirm"] parameters:param_dic success:^(id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        NSDictionary *dic = responseObject;
         kOrderDismiss;
        if ([dic[@"success"] boolValue]){
            
//            NSArray *ordersArr = responseObject[@"data"][@"orders"];
//            NSLog(@"%lu",(unsigned long)ordersArr.count);
//            NSDictionary *dic = ordersArr[0];
//            NSArray *array_order_items = [dic objectForKey:@"order_items"];
//            NSLog(@"%@",array_order_items);
//            
//            
//            callback(YES,array_order_items,nil);
            callback(YES,dic,nil);
        }else{
            callback(NO,dic,nil);
        }
        
        
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
         kOrderDismiss;
              callback(NO,nil,error);
    }];
    
}
+(void)getcouponInfo:(NSString *)couponId callback:(myCallback)callback{
    NSDictionary *param_dic = [NSDictionary dictionaryWithObject:couponId forKey:@"couponId"];
    RequestManager *manager = [RequestManager manager];
//    kOrderLoading;
    [manager bkDataRequest:RequestMethodPost URLString:[BKMainCommon ServicesURL:@"integralCoupon/info"] parameters:param_dic success:^(id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
//         kOrderDismiss;
        NSDictionary *dic = responseObject;
        if ([dic[@"success"] boolValue]){
            callback(YES,dic[@"data"],nil);

        }else{
            callback(NO,dic,nil);
        }
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
//         kOrderDismiss;
        callback(NO,nil,error);
    }];
}
+(void)exchangeCoupon:(NSString *)couponId mycallBack:(myCallback)callback{
    NSDictionary *param_dic = [NSDictionary dictionaryWithObject:couponId forKey:@"couponId"];
    RequestManager *manager = [RequestManager manager];
    kOrderLoading;
    [manager bkDataRequest:RequestMethodPost URLString:[BKMainCommon ServicesURL:@"integralCoupon/exchangeCoupon"] parameters:param_dic success:^(id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
         kOrderDismiss;
        NSDictionary *dic = responseObject;
        if ([dic[@"success"] boolValue]){
            callback(YES,nil,nil);
            
        }else{
            callback(NO,dic,nil);
        }

        
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
         kOrderDismiss;
        callback(NO,nil,error);

    }];
}
@end
